package com.ndp.fb.walle.controller;

import com.alibaba.fastjson.JSON;
import com.ndp.fb.constant.CommonConstants;
import com.ndp.fb.enums.ErrorType;
import com.ndp.fb.exception.CheckedException;
import com.ndp.fb.rdb.model.EcFont;
import com.ndp.fb.rdb.model.Pager;
import com.ndp.fb.rdb.model.User;
import com.ndp.fb.util.StringUtil;
import com.ndp.fb.walle.business.EcFontSercie;
import com.ndp.fb.walle.model.vo.OutputResult;
import com.ndp.fb.walle.model.vo.PageResult;
import com.ndp.fb.walle.model.vo.adpublishcondition.param.SearchListParam;
import com.ndp.fb.walle.model.vo.ectemplate.param.EcTemplatePreviewElementParam;
import com.ndp.fb.walle.util.ResponseUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by infi.he on 2016/4/26.
 */
@RestController
@RequestMapping("/ecfont")
public class EcFontController {

    Logger logger = LoggerFactory.getLogger(EcFontController.class);

    @Autowired
    EcFontSercie ecFontSercie;

    /**
     * 获取 font列表
     *
     * @return
     */
    @RequestMapping("findAll")
    public Map<String, Object> findAll(@RequestBody SearchListParam searchListParam, HttpServletRequest req) {
        logger.info("EcFontController findAll.");
        Map<String, Object> data = new HashMap<>();
        User user = (User) req.getSession().getAttribute("user");
        Integer sizeNo = searchListParam.getPSize() == null ? CommonConstants.DEFAULT_PAGE_SIZE_100 : searchListParam.getPSize();
        Integer firstResult = searchListParam.getCPage() == null ? 0 : (searchListParam.getCPage() - 1) * sizeNo;
        Pager<EcFont> results = ecFontSercie.findPager(user.getOrgId(), firstResult, sizeNo);
        if(results==null){
            results = new Pager<>();
            results.setPageIndex(sizeNo);
            results.setTotalSize(0L);
        }
        // 计算分页结果
        long tSize = results.getTotalSize();
        float nrOfPages = (float) tSize / sizeNo;
        int tPage = (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages);
        PageResult pageResult = new PageResult(tPage, searchListParam.getCPage(), searchListParam.getPSize(), tSize);
        // 封装响应结果
        data.put("fonts", results.getResultList());
        data.put("paginator", pageResult);
        return data;
    }


    /**
     * FONT 上传
     */
    @RequestMapping("upload")
    public Long upload(HttpServletRequest req) throws Exception {
        logger.info("EcFontController upload() begin.");
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) req;
        User user = (User) req.getSession().getAttribute("user");
        MultiValueMap<String, MultipartFile> multiFileMap = multiRequest.getMultiFileMap();
        String fontName = req.getParameter("fontName");
        String fontWeight = req.getParameter("fontWeight");

        List<MultipartFile> lists = new ArrayList<>();
        for (Map.Entry<String, List<MultipartFile>> stringListEntry : multiFileMap.entrySet()) {
            lists.add(stringListEntry.getValue().get(0));
        }

        ecFontSercie.uploadFont(lists, req.getRealPath("/"), fontName, fontWeight, user);
        logger.info("EcFontController upload.");
        return 1L;
    }

    /**
     * fontName重名校验
     * @param param
     */
    @RequestMapping("validate")
    public Long validate(@RequestBody EcFont param, HttpServletRequest req)throws Exception{
        User user = (User) req.getSession().getAttribute("user");
        if(param != null && StringUtil.isNotEmpty(param.getFontName())){
            EcFont ecFont = ecFontSercie.findByFontName(user.getOrgId(), param.getFontName());
            if(ecFont == null)
                return 1L;
            else if(ecFont.getId().equals(param.getId()))
                return 1L;
            else
                return 2L;
        } else {
            throw new CheckedException(ErrorType.PARAM_EXCEPTION);
        }
    }

    /**
     * fontName重名校验
     * @param param
     */
    @RequestMapping("getByTmpl")
    public List<EcFont> getByTmpl(@RequestBody EcTemplatePreviewElementParam param)throws Exception{
        if(param != null && param.getTemplateId() != null && param.getTemplateId() != 0L ){
            return ecFontSercie.getByTemplateId(param.getTemplateId());
        } else {
            throw new CheckedException(ErrorType.PARAM_EXCEPTION);
        }
    }


}
